<template>
    <div class="workflow-list">
        <div class="workflow-list__header">
            <h2>工作流管理</h2>
            <div class="actions">
                <el-upload
                    class="upload-button"
                    :action="null"
                    :auto-upload="false"
                    :show-file-list="false"
                    accept=".json"
                    @change="handleImport"
                >
                    <el-button>导入工作流</el-button>
                </el-upload>
                <el-button type="primary" @click="handleCreate">
                    创建工作流
                </el-button>
            </div>
        </div>

        <el-table
            v-loading="loading"
            :data="workflows"
            border
            style="width: 100%"
            row-key="id"
        >
            <el-table-column prop="name" label="名称" min-width="150">
                <template #default="{ row }">
                    <el-link type="primary" @click="handleEdit(row)">
                        {{ row.name }}
                    </el-link>
                </template>
            </el-table-column>
            <el-table-column prop="category" label="分类" width="120" />
            <el-table-column label="预览图" width="120">
                <template #default="{ row }">
                    <el-image
                        :src="row.thumbnail"
                        style="width: 80px; height: 80px"
                        fit="cover"
                        :preview-src-list="[row.thumbnail]"
                    />
                </template>
            </el-table-column>
            <el-table-column label="标签" min-width="200">
                <template #default="{ row }">
                    <el-tag
                        v-for="tag in row.tags"
                        :key="tag"
                        size="small"
                        style="margin-right: 4px"
                    >
                        {{ tag }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="统计" width="200">
                <template #default="{ row }">
                    <div class="stats">
                        <el-tooltip content="使用次数">
                            <span>
                                <el-icon><Download /></el-icon>
                                {{ row.stats.uses }}
                            </span>
                        </el-tooltip>
                        <el-tooltip content="点赞数">
                            <span>
                                <el-icon><Star /></el-icon>
                                {{ row.stats.likes }}
                            </span>
                        </el-tooltip>
                        <el-tooltip content="浏览量">
                            <span>
                                <el-icon><View /></el-icon>
                                {{ row.stats.views }}
                            </span>
                        </el-tooltip>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="状态" width="100">
                <template #default="{ row }">
                    <el-tag :type="row.isPublic ? 'success' : 'info'">
                        {{ row.isPublic ? '已发布' : '未发布' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="260" fixed="right">
                <template #default="{ row }">
                    <el-button-group>
                        <el-button
                            size="small"
                            type="primary"
                            :disabled="!row || (!row.id && !row._id)"
                            @click="handleEdit(row)"
                        >
                            <el-icon><Edit /></el-icon>
                            编辑
                        </el-button>
                        <el-button
                            size="small"
                            type="info"
                            :disabled="!row || (!row.id && !row._id)"
                            @click="handlePreview(row)"
                        >
                            <el-icon><View /></el-icon>
                            预览
                        </el-button>
                        <el-button
                            size="small"
                            type="danger"
                            :disabled="!row || (!row.id && !row._id)"
                            @click="handleDelete(row)"
                        >
                            <el-icon><Delete /></el-icon>
                            删除
                        </el-button>
                    </el-button-group>
                </template>
            </el-table-column>
        </el-table>

        <!-- 导入预览对话框 -->
        <el-dialog
            v-model="importPreview.visible"
            title="导入预览"
            width="60%"
            :close-on-click-modal="false"
        >
            <div class="import-preview" v-loading="importPreview.loading">
                <div class="preview-header">
                    <div class="basic-info">
                        <h3>{{ importPreview.data?.name }}</h3>
                        <p class="description">{{ importPreview.data?.description }}</p>
                        <div class="meta">
                            <el-tag size="small">作者: {{ importPreview.data?.author }}</el-tag>
                            <el-tag size="small" type="info">版本: {{ importPreview.data?.version }}</el-tag>
                            <el-tag size="small" type="success">分类: {{ importPreview.data?.category }}</el-tag>
                        </div>
                        <div class="tags">
                            <el-tag
                                v-for="tag in importPreview.data?.tags"
                                :key="tag"
                                size="small"
                                class="tag"
                            >
                                {{ tag }}
                            </el-tag>
                        </div>
                    </div>
                    <div class="preview-image">
                        <el-image
                            v-if="importPreview.data?.thumbnail"
                            :src="importPreview.data.thumbnail"
                            fit="contain"
                            :preview-src-list="[importPreview.data.thumbnail]"
                        />
                    </div>
                </div>

                <div class="workflow-config">
                    <h4>工作流配置</h4>
                    <el-alert
                        v-if="importPreview.nameExists"
                        type="warning"
                        :closable="false"
                        show-icon
                    >
                        已存在同名工作流，导入后将自动重命名
                    </el-alert>
                    <el-form :model="importPreview.data" label-width="100px">
                        <el-form-item label="工作流名称">
                            <el-input v-model="importPreview.data.name" />
                        </el-form-item>
                        <el-form-item label="工作流描述">
                            <el-input
                                v-model="importPreview.data.description"
                                type="textarea"
                                rows="2"
                            />
                        </el-form-item>
                        <el-form-item label="配置预览">
                            <el-collapse>
                                <el-collapse-item title="ComfyUI JSON">
                                    <pre class="json-preview">{{ formatJson(importPreview.data?.comfyuiJson) }}</pre>
                                </el-collapse-item>
                            </el-collapse>
                        </el-form-item>
                    </el-form>
                </div>
            </div>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="importPreview.visible = false">取消</el-button>
                    <el-button
                        type="primary"
                        :loading="importPreview.importing"
                        @click="confirmImport"
                    >
                        确认导入
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 导出配置对话框 -->
        <el-dialog
            v-model="exportConfig.visible"
            title="导出配置"
            width="500px"
        >
            <div class="export-config">
                <el-form :model="exportConfig.options" label-width="120px">
                    <!-- 导出内容选项 -->
                    <el-form-item label="导出内容">
                        <el-checkbox-group v-model="exportConfig.options.includes">
                            <el-checkbox label="basic" border>基本信息</el-checkbox>
                            <el-checkbox label="workflow" border>工作流配置</el-checkbox>
                            <el-checkbox label="thumbnail" border>预览图</el-checkbox>
                            <el-checkbox label="stats" border>统计信息</el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>

                    <!-- 文件命名模板 -->
                    <el-form-item label="文件名模板">
                        <el-input
                            v-model="exportConfig.options.nameTemplate"
                            placeholder="例如: {name}-{version}"
                        >
                            <template #append>
                                <el-select v-model="exportConfig.options.nameTemplate" style="width: 150px">
                                    <el-option label="{name}-{version}" value="{name}-{version}" />
                                    <el-option label="{name}-v{version}" value="{name}-v{version}" />
                                    <el-option label="{name}_{date}" value="{name}_{date}" />
                                    <el-option label="custom" value="custom">自定义</el-option>
                                </el-select>
                            </template>
                        </el-input>
                        <div class="form-help">
                            可用变量: {name} - 名称, {version} - 版本, {date} - 日期
                        </div>
                    </el-form-item>

                    <!-- 导出格式 -->
                    <el-form-item label="导出格式">
                        <el-radio-group v-model="exportConfig.options.format">
                            <el-radio-button label="json">JSON</el-radio-button>
                            <el-radio-button label="yaml">YAML</el-radio-button>
                        </el-radio-group>
                    </el-form-item>

                    <!-- 压缩选项 -->
                    <el-form-item label="压缩选项">
                        <el-switch
                            v-model="exportConfig.options.compress"
                            active-text="压缩文件"
                        />
                    </el-form-item>

                    <!-- 高级选项 -->
                    <el-collapse>
                        <el-collapse-item title="高级选项">
                            <el-form-item label="导出版本">
                                <el-radio-group v-model="exportConfig.options.version">
                                    <el-radio label="current">当前版本</el-radio>
                                    <el-radio label="all">所有版本</el-radio>
                                    <el-radio label="custom">指定版本</el-radio>
                                </el-radio-group>
                                <el-input
                                    v-if="exportConfig.options.version === 'custom'"
                                    v-model="exportConfig.options.customVersion"
                                    placeholder="输入版本号"
                                    style="margin-top: 10px"
                                />
                            </el-form-item>

                            <el-form-item label="元数据">
                                <el-checkbox-group v-model="exportConfig.options.metadata">
                                    <el-checkbox label="createTime">创建时间</el-checkbox>
                                    <el-checkbox label="updateTime">更新时间</el-checkbox>
                                    <el-checkbox label="author">作者信息</el-checkbox>
                                </el-checkbox-group>
                            </el-form-item>
                        </el-collapse-item>
                    </el-collapse>
                </el-form>
            </div>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="exportConfig.visible = false">取消</el-button>
                    <el-button
                        type="primary"
                        :loading="exportConfig.exporting"
                        @click="handleExportWithConfig"
                    >
                        导出
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Download, Star, View, Edit, Delete } from '@element-plus/icons-vue';
import { workflowApi } from '@/api/workflow';
import type { WorkflowTemplate } from '@/types';

const router = useRouter();
const workflows = ref<WorkflowTemplate[]>([]);
const loading = ref(false);

// 导入预览状态
const importPreview = ref({
    visible: false,
    loading: false,
    importing: false,
    nameExists: false,
    data: null as any,
    file: null as File | null
});

// 导出配置状态
const exportConfig = ref({
    visible: false,
    exporting: false,
    currentWorkflow: null as WorkflowTemplate | null,
    options: {
        includes: ['basic', 'workflow'],
        nameTemplate: '{name}-{version}',
        format: 'json',
        compress: false,
        version: 'current',
        customVersion: '',
        metadata: [] as string[]
    }
});

const loadWorkflows = async () => {
    try {
        loading.value = true;
        const { data } = await workflowApi.getAllWorkflows();
        if (!data?.data) {
            throw new Error('获取工作流列表失败');
        }
        workflows.value = data.data;
        workflows.value = workflows.value.map(workflow => ({
            ...workflow,
            id: workflow.id || workflow._id // 兼容 MongoDB 的 _id
        }));
        console.log('Loaded workflows:', workflows.value.length);
    } catch (error) {
        ElMessage.error('加载工作流列表失败');
        console.error('Load workflows error:', error);
    } finally {
        loading.value = false;
    }
};

const handleCreate = () => {
    console.log('Creating new workflow');
    router.push('/workflow/create');
};

const handleEdit = (workflow: WorkflowTemplate) => {
    const workflowId = workflow?.id || workflow?._id;
    if (!workflow || !workflowId) {
        ElMessage.error('无效的工作流');
        return;
    }
    console.log('Editing workflow:', workflowId);
    router.push(`/workflow/${workflowId}/edit`);
};

const handlePreview = (workflow: WorkflowTemplate) => {
    const workflowId = workflow?.id || workflow?._id;
    if (!workflow || !workflowId) {
        ElMessage.error('无效的工作流');
        return;
    }
    console.log('Previewing workflow:', workflowId);
    router.push(`/workflow/${workflowId}`);
};

const handleDelete = async (workflow: WorkflowTemplate) => {
    try {
        const workflowId = workflow?.id || workflow?._id;
        if (!workflow || !workflowId) {
            ElMessage.error('无效的工作流');
            return;
        }
        await ElMessageBox.confirm(
            '确定要删除该工作流吗？此操作不可恢复。',
            '提示',
            {
                type: 'warning',
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }
        );
        
        console.log('Deleting workflow:', workflowId);
        await workflowApi.deleteWorkflow(workflowId);
        ElMessage.success('删除成功');
        loadWorkflows();
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除失败');
            console.error('Delete workflow error:', error);
        }
    }
};

const handleExport = (workflow: WorkflowTemplate) => {
    exportConfig.value.currentWorkflow = workflow;
    exportConfig.value.visible = true;
};

// 处理配置导出
const handleExportWithConfig = async () => {
    if (!exportConfig.value.currentWorkflow) return;

    try {
        exportConfig.value.exporting = true;

        // 构建导出选项
        const options = {
            ...exportConfig.value.options,
            workflowId: exportConfig.value.currentWorkflow.id
        };

        // 调用导出 API
        const blob = await workflowApi.exportWorkflow(options);

        // 生成文件名
        const filename = generateExportFilename(
            exportConfig.value.currentWorkflow,
            exportConfig.value.options
        );

        // 下载文件
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = filename;
        link.click();
        window.URL.revokeObjectURL(url);

        exportConfig.value.visible = false;
        ElMessage.success('导出成功');
    } catch (error) {
        ElMessage.error('导出失败');
        console.error('Export workflow error:', error);
    } finally {
        exportConfig.value.exporting = false;
    }
};

// 生成导出文件名
const generateExportFilename = (workflow: WorkflowTemplate, options: typeof exportConfig.value.options) => {
    const date = new Date().toISOString().split('T')[0];
    const template = options.nameTemplate
        .replace('{name}', workflow.name)
        .replace('{version}', workflow.version)
        .replace('{date}', date);
    
    const extension = options.compress ? '.zip' : `.${options.format}`;
    return template + extension;
};

// 格式化 JSON 显示
const formatJson = (json: any) => {
    try {
        return JSON.stringify(json, null, 2);
    } catch {
        return '';
    }
};

// 检查工作流名称是否存在
const checkWorkflowName = async (name: string) => {
    try {
        const response = await workflowApi.checkName(name);
        importPreview.value.nameExists = response.exists;
    } catch (error) {
        console.error('Check workflow name error:', error);
    }
};

// 修改导入处理函数
const handleImport = async (file: { raw: File }) => {
    try {
        if (!file.raw.name.endsWith('.json')) {
            ElMessage.error('请上传 JSON 格式的工作流文件');
            return;
        }

        importPreview.value.loading = true;
        importPreview.value.visible = true;
        importPreview.value.file = file.raw;

        const reader = new FileReader();
        reader.onload = async (e) => {
            try {
                const content = e.target?.result as string;
                const workflowData = JSON.parse(content);
                
                // 检查工作流名称
                if (workflowData.name) {
                    await checkWorkflowName(workflowData.name);
                }

                importPreview.value.data = workflowData;
            } catch (error) {
                ElMessage.error('工作流文件格式错误');
                console.error('Parse workflow file error:', error);
                importPreview.value.visible = false;
            }
            importPreview.value.loading = false;
        };
        reader.readAsText(file.raw);
    } catch (error) {
        ElMessage.error('导入失败');
        console.error('Import workflow error:', error);
        importPreview.value.loading = false;
        importPreview.value.visible = false;
    }
};

// 确认导入
const confirmImport = async () => {
    if (!importPreview.value.file || !importPreview.value.data) {
        return;
    }

    try {
        importPreview.value.importing = true;

        // 创建 FormData
        const formData = new FormData();
        formData.append('file', importPreview.value.file);
        formData.append('data', JSON.stringify(importPreview.value.data));

        await workflowApi.importWorkflow(formData);
        ElMessage.success('导入工作流成功');
        loadWorkflows();
        importPreview.value.visible = false;
    } catch (error) {
        ElMessage.error('导入失败');
        console.error('Import workflow error:', error);
    } finally {
        importPreview.value.importing = false;
    }
};

onMounted(() => {
    console.log('Loading workflow list');
    loadWorkflows();
});
</script>

<style lang="scss" scoped>
.workflow-list {
    padding: 20px;

    &__header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
    }

    .stats {
        display: flex;
        gap: 15px;

        span {
            display: flex;
            align-items: center;
            gap: 4px;
            color: #666;
        }
    }

    .actions {
        display: flex;
        gap: 10px;
    }

    .upload-button {
        display: inline-block;
    }

    .import-preview {
        .preview-header {
            display: flex;
            gap: 20px;
            margin-bottom: 20px;

            .basic-info {
                flex: 1;

                h3 {
                    margin: 0 0 10px;
                }

                .description {
                    color: #666;
                    margin-bottom: 10px;
                }

                .meta {
                    margin-bottom: 10px;
                    .el-tag {
                        margin-right: 8px;
                    }
                }

                .tags {
                    .tag {
                        margin: 0 4px 4px 0;
                    }
                }
            }

            .preview-image {
                width: 200px;
                .el-image {
                    width: 100%;
                    height: 150px;
                    border-radius: 4px;
                }
            }
        }

        .workflow-config {
            h4 {
                margin: 0 0 16px;
            }

            .json-preview {
                background: #f5f7fa;
                padding: 12px;
                border-radius: 4px;
                max-height: 300px;
                overflow: auto;
                font-family: monospace;
                font-size: 12px;
            }
        }
    }

    .export-config {
        .el-checkbox-group {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
        }

        .form-help {
            font-size: 12px;
            color: #909399;
            margin-top: 4px;
        }

        :deep(.el-collapse) {
            margin-top: 20px;
            border: none;

            .el-collapse-item__header {
                font-size: 14px;
                color: #409eff;
            }
        }
    }

    .el-button-group {
        .el-button {
            .el-icon {
                margin-right: 4px;
            }
        }
    }
}
</style> 